<?php
// +----------------------------------------------------------------------
// | PHP [ JUST YOU ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2017 http://www.jyphp.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: FlyingPig <flyingpigfp@163.com>
// +----------------------------------------------------------------------

namespace App\Logic;


use App\Exceptions\ApiException;
use App\Model\Room\CreateRoomRec;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;


class RoomRecLogic extends Logic
{

    /**
     * 查看当前拥有房卡是否满足开房
     * @param $uid
     * @param $board_choose
     * @throws ApiException
     */
    public function checkRoomTicket($uid, $board_choose)
    {
        $use_cards = $this->returnRoomCard($board_choose);
        if (!DB::table('t_player_info')->where('id', $uid)->where('room_ticket', '>=', $use_cards)->value('id')) {
            throw new ApiException('当前房卡数量不够', 1);
        }
    }


    /**
     * 创建房间
     * @param $param
     * @param $uid
     * @param $number
     * @return int|array
     * @throws ApiException
     */
    public function createRoom($param, $uid, $rand_room)
    {
        $data = [
            'uid' => $uid,
            'player_num' => $param['player_num'],
            'board_choose' => $param['board_choose'],
            'use_cards' => $this->returnRoomCard($param['board_choose']),
            'password' => (int)$rand_room,
            'rule' => '贵阳麻将|冲锋鸡',
            'create_time' => date('Y-m-d H:i:s')
        ];
        //如果有俱乐部id则插入
        if (!empty($param['club_id'])) {
            $data['clubid'] = $param['club_id'];
            $room_id        = DB::table('t_create_room_rec')->insertGetId($data);
        } else {
            $object = DB::table('t_create_room_rec')->where('clubid', 0)->where('uid', $uid)->where('status', 1)->first();
            if (!empty($object)) {
                //如果普通房间还存在,直接返回，不继续创建
                return [
                    'room_info' => [
                        'room_id' => $object->id,
                        'uid' => $uid,
                        'room_pwd' => $object->password,
                        'board' => $object->board_choose,
                        'cost_ticket' => $object->use_cards
                    ]
                ];
            }
            $room_id = DB::table('t_create_room_rec')->insertGetId($data);
        }
        return ['id' => $room_id, 'board_choose' => $param['board_choose'],'use_cards' => $data['use_cards']];
    }


    /**
     * 激活房间
     * @param $id
     * @param $uid
     * @return mixed
     * @throws ApiException
     */
    public function action($id, $uid)
    {
        if (DB::table('t_create_room_rec')
            ->where('id', $id)
            ->where('uid', $uid)
            ->where('status', 0)
            ->update(['status' => 1])
        ) {
            return true;
        }
        throw new ApiException('action room failure', 2);
    }


    /**
     * 扣除个人房卡
     * @param $uid
     * @param $board_choose
     * @throws ApiException
     */
    public function reduce($uid, $board_choose)
    {
        $use_cards = $this->returnRoomCard($board_choose);
        if (!DB::table('t_player_info')->where('id', $uid)->update(['room_ticket' => DB::raw("room_ticket - $use_cards")])) {
            throw new ApiException('扣除房卡失败');
        }
    }


    /**
     * 解散房间
     * @param $id
     * @param $uid
     * @return
     * @throws ApiException
     */
    public function dissolutionLogic($id, $uid)
    {
        if (!empty(Redis::hGet('ROOM_PLAYER_NUM', $id))) {
            throw new ApiException('房间有人不能解散', 6);
        }
        $object = CreateRoomRec::where('id', $id)
            ->where('uid', $uid)
            ->where('service_id', 0)
            ->where('desk_id', 0)
            ->where('status', '<', 3)
            ->first(['id', 'order_id', 'password', 'use_cards']);
        if (empty($object)) {
            throw new ApiException('当前房间状态不能解散', 6);
        }
        if (!DB::table('t_player_info')->where('id', $uid)->update(['room_ticket' => DB::raw("room_ticket + $object->use_cards")])) {
            throw new ApiException('退还房卡失败');
        }
        //更新房间状态
        $object->status = 4;
        $object->save();
        Redis::eval(file_get_contents(base_path() . '/redisscript/return_room.lua'), 2, env('REDIS_ROOM_KEY'), $object->password);
    }

    /**
     * 返回Redis中的随机数
     * @return mixed
     * @throws ApiException
     */
    public  function redisRand()
    {
        $pwd = Redis::spop('Q_' . env('REDIS_ROOM_KEY'));
        if (empty($pwd)) {
            SmsLogic::instance()->sendRedisError();
            throw new ApiException('随机房间号为空');
        }
        return $pwd;
    }


    private function returnRoomCard($board_choose)
    {
        if ($board_choose == 4) {
            return 3;
        } elseif ($board_choose == 8) {
            return 5;
        } else {
            throw new ApiException('局数有误!请选择4或8局');
        }
    }

}